﻿//定义应用全局对象
window.ABUS = {
    Const: {
        param: "__param__",
        result: "__result__",
        result_param: "result_param"
    },
    Fn: {},
    env: "prd"//dev:开发 prd：生产,
};

//监听窗口改变事件，重新计算跟字体大小
$(window).on('resize', function () {
    $('html').css({
        'font-size': 100 * ($(window).width() / 750)
    })
}).trigger('resize');
//初始化
$(function () {
    //设置常用对象引用
    var abus = ABUS;
    var fn = abus.Fn;
    var Const = abus.Const;
    var $body = $(document.body);
    window.isDrag = false;

    (function () {
        if (!window[ABUS.Const.param]) {
            window[ABUS.Const.param] = {}
        }
        //初始化传参
        // var __param__ = window[ABUS.Const.param] = __param__?__param__:{};
        var url = window.location.href
            , start = url.indexOf("?") == -1 ? null : url.indexOf("?") + 1
            , end = url.indexOf("#")
            , param;
        if (end == -1) {
            param = url.slice(start);
        } else {
            param = url.slice(start, end);
        }
        if (param.search('=') > -1) {
            param = param.split("&");
            $.each(param, function (i, j) {
                window[ABUS.Const.param][j.split('=')[0]] = decodeURIComponent(j.split('=')[1]);
            });
        }
    })();


    $(window).on('unload', function () {
        // if(window[Const.result]){
        fn.winClose();
        // }
    });

    $.fn.renderTemp = function (data) {
        var that = this;
        var tp = $.trim(that.children("script[type='text/template']:first").html());

        if (!that.data('tp') && tp != '') {
            that.data('tp', tp);
        }

        this.html(function () {
            return _.template(that.data('tp'))(data)
        })
    };

    //监听点击事件，关闭视窗浮层
    $body.on("touchend", ".closeLayer", function () {
        fn.closeModal();
    });

    //通用ajax
    fn.get = function (options) {
        var url = options.url;
        // if (abus.env == 'dev') {
        //     // url = url.substr(url.lastIndexOf('/') + 1).replace(/_/g, "/").replace(".json", "");
        //     url = 'simdata/' + url + '.json'
        // }else{
        //     url = options.url ? _root_ + options.url : './simdata/common.json';
        // }
        var data = options.data ? options.data : {};
        var success = options.success ? options.success : _.noop;
        var _success = function (data) {
            // if(data.message && data.message.search(/登录失败|登陆失败/)>-1){
            //     fn.alert({
            //         type:"error",
            //         title:"请重新登录"
            //     });
            //     setTimeout(function () {
            //         fn.page_goto({
            //             url:"/wwwroot/denglu/denglu.html"
            //         })
            //     },1500);
            // }
            success(data);
        }
        var error = options.error ? options.error : _.noop;
        // var type = options.type ? $.trim(options.type).toLowerCase() : 'get';

        // if (type == 'post') {
        //     $.post(url, data, success, 'json');
        // } else if (type == 'put') {
        //     $.ajax({
        //         url: url,
        //         data: data,
        //         success: success,
        //         dataType: 'json',
        //         type: type
        //     });
        // } else {
        //     $.getJSON(url, data, success);
        // }
        if (abus.env == 'prd') {
            $.ajax({
                url: url,
                data: data,
                success: _success,
                error:error,
                // dataType: 'jsonp'
            });
        }else{
            $.getJSON(url, data, success);
        }
    };

    //关闭遮罩层后移除节点
    fn.closeModal = function (cb) {
        if ($('.main_modal_wrap:first').find("[unhide]").length > 0) return false;
        $('.main_modal_wrap:first').fadeOut('fast', function () {
            $(this).remove();
            cb ? cb() : null
        })
    };

    //模态框父类
    var Modal = function (options) {
        var that = this;
        this.$el = $("<div class='main_modal_wrap'></div>");
        //遮罩层模板
        var tp_mask = _.template('<div class="main_modal_inner" style="<%=!mask?\"background:none;\":\"\"%>"><%=content%></div>');
        //遮罩层接口
        this.doMask = function (options) {
            //合并配置
            // _.defaults(options, {
            // });
            //加载到页面
            this.$el.html(tp_mask(options));
            $body.append(this.$el);
            //显示
            this.$el.fadeIn('fast', function () {
                _.isFunction(options.onShow) ? options.onShow.call(that.$el) : null;
            });
        };
        this.mask = _.isUndefined(options.mask) ? true : options.mask;
        this.options = options;
        this.template = options.template;

        this.$el.on('click', '[data-submit-btn]', function () {
            _.isFunction(options.onSubmit) ? options.onSubmit.call(that.$el) : null;
        });
        this.$el.on('click', '[data-cancel-btn]', function () {
            _.isFunction(options.onCancel) ? options.onCancel.call(that.$el) : null;
        });
        return this;
    };
    Modal.prototype.show = function () {
        fn.closeModal();
        //调用遮罩层
        this.doMask($.extend({
            content: this.template({
                data: this.options
            }),
            mask: this.mask
        }, this.options));
        return this;
    };

    //操作结果提示层模板
    var tp_alert = _.template('' +
        '<%if(data.type == "success"){%>' +
        '<div class="payment_success radius_small closeLayer">' +
        '<%}else{%>' +
        '<div class="payment_failed radius_small closeLayer">' +
        '<%}%>' +
        '<span class="font20 colorfff"><%=data.title%></span>' +
        '</div>');
    //操作结果提示层接口
    fn.alert = function (options) {
        //合并配置
        if (options.type != "success" && options.type != "error") {
            console.error("类型错误");
            return;
        }
        options.title = options.title ? options.title : "";
        options.template = tp_alert;
        options.onShow = options.onShow ? options.onShow : function () {
            var $this = $(this)
                // setTimeout(function () {
                //     fn.closeModal();
                // }, 1000)

            };
        //调用遮罩层
        new Modal(options).show();
    };

    fn.loading = function (options) {
        options = options ? options : {};
        options.title = options.title ? options.title : "";
        options.mask = false;
        options.template = _.template('<div class="g_loading">加载中...</div>');
        options.onShow = options.onShow ? options.onShow : function () {
            };
        //调用遮罩层
        new Modal(options).show();
    };
    //微信支付提示层模板
    var tp_payment = _.template('\
        <div class="chat_payment radius_small">\
        <div class="payment_top">\
        <span class="font14 color284">确认结算</span>\
        </div>\
        <div class="payment_mid">\
        <span class="font18 color284">结算订单金额</span>\
        <span class="font18 colorf29 num">--.--</span>\
        <span class="font18 color284">元</span>\
        </div>\
        <div class="payment_bottom">\
        <div class="payment_bottom_left radius_big" data-cancel-btn>\
        <a class="font14 colorfff">取消</a>\
        </div>\
        <div class="payment_bottom_right radius_big" data-submit-btn>\
        <a class="font14 colorfff">确定</a>\
        </div>\
        </div>\
        </div>');
    //微信支付提示层接口
    fn.payment = function (options) {
        /*  options.template = tp_payment;*/
        options = $.extend({
            onShow: function () {
                var self = this;
                $(this).find(".num").text(options.price?options.price:0);
                $(this).on("touchend ", function (e) {
                    e.stopPropagation();
                });
            }
        }, options);

        options.template = options.template ? _.template(options.template) : tp_payment;
        //调用遮罩层
        new Modal(options).show();

    };
    //确认层模板
    var tp_confirm = _.template('\
        <div class="chat_payment radius_small">\
        <div class="payment_top">\
        </div>\
        <div class="payment_mid">\
        <span class="font18 color284"><%=data.title?data.title:"确认执行此操作？"%></span>\
        </div>\
        <div class="payment_bottom">\
        <div class="payment_bottom_left radius_big" data-cancel-btn>\
        <a class="font14 colorfff">取消</a>\
        </div>\
        <div class="payment_bottom_right radius_big" data-submit-btn>\
        <a class="font14 colorfff">确定</a>\
        </div>\
        </div>\
        </div>');
    //微信支付提示层接口
    fn.confirm = function (options) {
        /*  options.template = tp_confirm;*/
        options = $.extend({
            onShow: function () {
                var self = this;
                $(this).find(".num").text(options.price?options.price:0);
                $(this).on("touchend ", function (e) {
                    e.stopPropagation();
                });
            }
        }, options);

        options.template = options.template ? _.template(options.template) : tp_confirm;
        //调用遮罩层
        new Modal(options).show();

    };
    //静态信息提示层模板
    var tp_info = _.template('\
        <div class="charter_float_1">\
        <div class="charter_float radius_big">\
        <div class="charter_float_title">\
        <span class="font12 color71a">-infoModal title-</span>\
        </div>\
        <ul class="charter_float_content">\
        <li class="b1">\
        <span class="font16 color284">hello world!</span>\
        </li>\
        </ul>\
        </div>\
        <div class="charter_float_delete">\
        </div>\
        </div>');
    //静态信息提示层接口
    fn.info = function (options) {
        options = $.extend({}, options);

        options.template = options.template ? _.template(options.template) : tp_info;
        //调用遮罩层
        new Modal(options).show();
    };
    //滚动选择层接口
    fn.scrollSelect = function (options) {
        // options.template = tp_timeselect;
        //调用遮罩层
        // new Modal(options).show();
        //api:https://docs.mobiscroll.com/2-17-3/jquery/scroller#usage
        var id = options.id;
        if (!id) return;

        var mobiscrollInst = $(id).mobiscroll('getInst');
        if (mobiscrollInst._class == 'scroller') return true;
        $(id).mobiscroll('destroy').scroller(options);
        mobiscrollInst = $(id).mobiscroll('getInst');
        mobiscrollInst.show();
        return mobiscrollInst;
    };
    //日历模板
    var tp_calendar = _.template('\
        <div class="calendar_list radius_big">\
        <div class="cal1"></div>\
   </div>');
    fn.calendar = function (options) {
        options = $.extend({}, options);

        options.template = options.template ? _.template(options.template) : tp_calendar;
        //调用遮罩层
        new Modal(options).show();
    };

    //影院选择层模板
    var tp_cinema = _.template('\
        <div class="charter_float_1">\
        <div class="charter_float radius_big">\
        <div class="charter_float_title">\
        <span class="font12 color71a">-infoModal title-</span>\
        </div>\
        <ul class="charter_float_content">\
        <li class="b1">\
        <span class="font16 color284">hello world!</span>\
        </li>\
        </ul>\
        </div>\
        <div class="charter_float_delete">\
        </div>\
        </div>');
    //静态信息提示层接口
    fn.cinema = function (options) {
        options = $.extend({}, options);

        options.template = options.template ? _.template(options.template) : tp_cinema;
        //调用遮罩层
        new Modal(options).show();
    };

    //选择数量支付弹出层
    var tp_count = _.template('\
        <div class="charter_float_1">\
        <div class="charter_float radius_big">\
        <div class="charter_float_title">\
        <span class="font12 color71a">-infoModal title-</span>\
        </div>\
        <ul class="charter_float_content">\
        <li class="b1">\
        <span class="font16 color284">hello world!</span>\
        </li>\
        </ul>\
        </div>\
        <div class="charter_float_delete">\
        </div>\
        </div>');
    //静态信息提示层接口
    fn.count = function (options) {
        options = $.extend({}, options);

        options.template = options.template ? _.template(options.template) : tp_count;
        //调用遮罩层
        new Modal(options).show();
    };

    //确认是否删除弹出层
    var tp_delete = _.template('\
        <div class="charter_float_1">\
        <div class="charter_float radius_big">\
        <div class="charter_float_title">\
        <span class="font12 color71a">-infoModal title-</span>\
        </div>\
        <ul class="charter_float_content">\
        <li class="b1">\
        <span class="font16 color284">hello world!</span>\
        </li>\
        </ul>\
        </div>\
        <div class="charter_float_delete">\
        </div>\
        </div>');
    //静态信息提示层接口
    fn.delete = function (options) {
        options = $.extend({}, options);

        options.template = options.template ? _.template(options.template) : tp_delete;
        //调用遮罩层
        new Modal(options).show();
    };

    //奖品领取成功弹出层
    var tp_receive = _.template('\
        <div class="charter_float_1">\
        <div class="charter_float radius_big">\
        <div class="charter_float_title">\
        <span class="font12 color71a">-infoModal title-</span>\
        </div>\
        <ul class="charter_float_content">\
        <li class="b1">\
        <span class="font16 color284">hello world!</span>\
        </li>\
        </ul>\
        </div>\
        <div class="charter_float_delete">\
        </div>\
        </div>');
    //静态信息提示层接口
    fn.receive = function (options) {
        options = $.extend({}, options);

        options.template = options.template ? _.template(options.template) : tp_receive;
        //调用遮罩层
        new Modal(options).show();
    };

    //中奖弹出层
    var tp_win = _.template('\
        <div class="home_layer">\
        <div class="closeLayer"></div>\
        <div class="circle_content">\
        <img src="<%=data.picUrl%>"/>\
        </div>\
        <div class="circle_text">\
        <p class="font28 color140">抽到了<%=data.title%></p>\
        <p class="font24 color847">(记得截图联系客服抽奖哦!)</p>\
        </div>\
        <div class="receive_submit" data-submit-btn>\
        <span class="font30 color140">确定</span>\
        </div>\
        </div>');
    //静态信息提示层接口
    fn.win = function (options) {
        options = $.extend({}, options);

        options.template = options.template ? _.template(options.template) : tp_win;
        options.onSubmit = options.onSubmit ? options.onSubmit : function () {
            fn.closeModal()
        };
        //调用遮罩层
        new Modal(options).show();
    };

    //未中奖弹出层
    var tp_failed = _.template('\
        <div class="charter_float_1">\
        <div class="charter_float radius_big">\
        <div class="charter_float_title">\
        <span class="font12 color71a">-infoModal title-</span>\
        </div>\
        <ul class="charter_float_content">\
        <li class="b1">\
        <span class="font16 color284">hello world!</span>\
        </li>\
        </ul>\
        </div>\
        <div class="charter_float_delete">\
        </div>\
        </div>');
    //静态信息提示层接口
    fn.failed = function (options) {
        options = $.extend({}, options);

        options.template = options.template ? _.template(options.template) : tp_failed;
        options.onSubmit = options.onSubmit ? options.onSubmit : function () {
            fn.closeModal()
        };
        //调用遮罩层
        new Modal(options).show();
    };

    //U币不足弹出层
    var tp_short = _.template('\
        <div class="charter_float_1">\
        <div class="charter_float radius_big">\
        <div class="charter_float_title">\
        <span class="font12 color71a">-infoModal title-</span>\
        </div>\
        <ul class="charter_float_content">\
        <li class="b1">\
        <span class="font16 color284">hello world!</span>\
        </li>\
        </ul>\
        </div>\
        <div class="charter_float_delete">\
        </div>\
        </div>');
    //静态信息提示层接口
    fn.short = function (options) {
        options = $.extend({}, options);

        options.template = options.template ? _.template(options.template) : tp_short;
        //调用遮罩层
        new Modal(options).show();
    };

    //页面跳转传参
    fn.page_goto = function (options, callback) {
        var url = options.url;
        if (options.data) {
            url += '?' + $.param(options.data);
        }
        //有回调模式
        if (callback) {
            // var _win = window.open(options.url);
            // _win[Const.param] = options.data;
            window[Const.result] = function (data) {
                callback ? callback(data) : null;
            };
            var ifr = $("<iframe></iframe>");
            ifr.css({
                width: '100%',
                height: '100%',
                border: "1px ",
                position: 'absolute',
                top: 0,
                left: 0,
                zIndex: 999
            });
            ifr.prop('src', url + '?v=' + new Date().getTime());
            $('body').append(ifr);
            $('html').css('overflow-y', 'hidden');
            $('.header').hide();
        } else {
            //无回调模式
            // var url = window.location.href.split('?')[0];
            // var url = options.url;
            // if(options.data){
            //     url += '?' + $.param(options.data);
            // }
            window.location.href = url;
        }
    };

    //页面跳转传参
    fn.open_url = function (options, callback) {
        var url = window.location.href.split('?')[0];
        url += '?' + $.param(options.data);
        window.location.href = url;
    };

    //设置关闭回调
    fn.setResult = function (val) {
        window[Const.result_param] = val;
    };

    //窗口关闭
    fn.winClose = _.debounce(function () {
        if (_.isFunction(window.parent[Const.result])) {
            window.parent[Const.result](window[Const.result_param])
        } else {

        }
        setTimeout(function () {
            window.parent.$('.header').show();
            window.parent.$('html').css('overflow-y', 'auto');
            window.parent.$('iframe').remove();
        }, 0);
        return;
    }, 100, true);

    //倒计时
    fn.countDown = function (min, cb) {
        var time = parseInt(min,10) * 60;
        var timer = window.setInterval(function () {
            if(time === 0){
                window.clearInterval(timer);
                return false;
            }
            time--;
            cb(Math.floor(time/3600) + ':' + Math.floor(time%3600/60) + ':' + Math.floor(time%60),Math.ceil(time/60))
        },1000);
        return '';
    };

    //生成随机数
    fn.getNonceStr = function () {
        var s = '', i = 0;
        for (i; i <= 31; i++) {
            s += parseInt(Math.random() * 16, 10).toString(16)
        }
        return s.toUpperCase();
    };

    fn.getTimeStamp = function () {
        return new Date().getTime().toString().slice(0, 10)
    };

});


